// 路由器
const routes = require('./routes.js')

module.exports = {
  routes,
  // 获取匹配路由
  matchRoute (pathname, method) {
    let route = routes.find(item => {
      if (String(item.method).toLowerCase() !== method) {
        return false
      }
      if (item.path === pathname) {
        return true
      }
      if (item.path instanceof RegExp && item.path.test(pathname)) {
        return true
      }
      return false
    })
    return route
  },
  // 执行路由
  run (route, req, res) {
    let instance = null
    if (route.name) {
      instance = this[route.name]
      if (!instance) {
        instance = new route.service()
        this[route.name] = instance
      }
    } else {
      if (!route.instance) {
        route.instance = new route.service()
      }
      instance = route.instance
    }
    return instance[route.action](req, res)
  }
}